package com.jxpanda.spring.module.auth.core.authentication.manager;


import com.jxpanda.infrastructure.core.tollkit.ReflectionKit;
import com.jxpanda.spring.module.auth.core.authentication.token.CollaborativeAuthenticationToken;
import com.jxpanda.spring.module.auth.core.authentication.token.UserDetailsAuthenticationToken;
import com.jxpanda.spring.module.auth.core.user.OAuth2ReactiveUserDetailsRepository;
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;
import reactor.core.publisher.Mono;

public class UsernamePasswordRepositoryReactiveAuthenticationManager extends AbstractUserDetailsRepositoryReactiveAuthenticationManager {

    private final UserDetailsRepositoryReactiveAuthenticationManager userDetailsRepositoryReactiveAuthenticationManager;

    public UsernamePasswordRepositoryReactiveAuthenticationManager(OAuth2ReactiveUserDetailsRepository oAuth2ReactiveUserDetailsRepository) {
        super(oAuth2ReactiveUserDetailsRepository);
        this.userDetailsRepositoryReactiveAuthenticationManager = new UserDetailsRepositoryReactiveAuthenticationManager(oAuth2ReactiveUserDetailsRepository);
    }

    @Override
    public Mono<CollaborativeAuthenticationToken> authenticate(CollaborativeAuthenticationToken collaborativeAuthenticationToken) {
        return userDetailsRepositoryReactiveAuthenticationManager.authenticate(collaborativeAuthenticationToken)
                .filter(Authentication::isAuthenticated)
                .map(authenticationToken -> new UserDetailsAuthenticationToken<>(collaborativeAuthenticationToken.getOAuth2Request(), collaborativeAuthenticationToken.getClientRegistration(), ReflectionKit.cast(authenticationToken.getPrincipal())));
    }


}
